//
//  BindDeviceVC.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/5/26.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "DeviceBindVC.h"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"
#import "DeviceBindGuideVC.h"
#import "DeviceBindTipsVC.h"

#define KMainW [UIScreen mainScreen].bounds.size.width
#define KMainH [UIScreen mainScreen].bounds.size.height

@interface DeviceBindVC ()<AVCaptureMetadataOutputObjectsDelegate, UINavigationControllerDelegate> {
    float angle;
    BOOL isAni;
    BOOL isBinding;
    
    BOOL isFromLoadingVC;
    BOOL isBindOk;
}

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) AVCaptureDevice *device;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preview;
@property (nonatomic, weak)   UIImageView *line;
@property (nonatomic, assign) NSInteger distance;

@property (nonatomic, weak) IBOutlet UIView *conView;
@property (nonatomic, weak) IBOutlet UIImageView *stateIv;
@property (nonatomic, weak) IBOutlet UILabel *stateLb;

@end

@implementation DeviceBindVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化
    [self initView];
    
    
    [self removeGesture];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    //设置参数
    [self setupCamera];
    //添加定时器
    [self addTimer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopScanning];
}

- (void)setIsFromLoadingVC:(BOOL) isFrom {
    isFromLoadingVC = isFrom;
}

- (void)initView {
    [self.conView setHidden:YES];
    
    self.view.backgroundColor = [UIColor blackColor];
    CGFloat scanW = KMainW * 0.65;
    CGFloat padding = 10.0f;
    CGFloat labelH = 20.0f;
    CGFloat cornerW = 26.0f;
    CGFloat marginX = (KMainW - scanW) * 0.5;
    CGFloat marginY = (KMainH - scanW - padding - labelH) * 0.5;
    
    //遮盖视图
    for (int i = 0; i < 4; i++) {
        UIView *cover = [[UIView alloc] initWithFrame:CGRectMake(0, (marginY + scanW) * i, KMainW, marginY + (padding + labelH) * i)];
        if (i == 2 || i == 3) {
            cover.frame = CGRectMake((marginX + scanW) * (i - 2), marginY, marginX, scanW);
        }
        cover.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];
        [self.view addSubview:cover];
        [self.view sendSubviewToBack:cover];
    }
    
    //扫描视图
    UIView *scanView = [[UIView alloc] initWithFrame:CGRectMake(marginX, marginY, scanW, scanW)];
    [self.view addSubview:scanView];
    
    //扫描线
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, scanW, 2)];
    [self drawLineForImageView:line];
    [scanView addSubview:line];
    self.line = line;
    
    //边框
    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, scanW, scanW)];
    borderView.layer.borderColor = [[UIColor whiteColor] CGColor];
    borderView.layer.borderWidth = 1.0f;
    [scanView addSubview:borderView];
    
    //扫描视图四个角
    for (int i = 0; i < 4; i++) {
        CGFloat imgViewX = (scanW - cornerW) * (i % 2);
        CGFloat imgViewY = (scanW - cornerW) * (i / 2);
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(imgViewX, imgViewY, cornerW, cornerW)];
        if (i == 0 || i == 1) {
            imgView.transform = CGAffineTransformRotate(imgView.transform, M_PI_2 * i);
        }else {
            imgView.transform = CGAffineTransformRotate(imgView.transform, - M_PI_2 * (i - 1));
        }
        [self drawImageForImageView:imgView];
        [scanView addSubview:imgView];
    }
    
    // 顶部title
    CGSize size = [[UIApplication sharedApplication] statusBarFrame].size;
    UIView *topBar = [[UIView alloc] initWithFrame:CGRectMake(0, size.height, size.width, 44)];
    topBar.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0f];
    [self.view addSubview:topBar];
    float height = 25;
    UIButton *bt = [[UIButton alloc] initWithFrame:CGRectMake(16, 22-height/2, height, height)];
    [bt setBackgroundImage:[UIImage imageNamed:@"img_close_x"] forState:UIControlStateNormal];
    [[bt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        if (self->isBindOk && !self->isFromLoadingVC) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"TabBarControllerID"];
            [self.navigationController pushViewController:vc animated:NO];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    [topBar addSubview:bt];
    if (!self->isFromLoadingVC) {
        height = 22;
        bt = [[UIButton alloc] initWithFrame:CGRectMake(topBar.frame.size.width-16-height, 22-height/2, height, height)];
        [bt setBackgroundImage:[UIImage imageNamed:@"img_question"] forState:UIControlStateNormal];
        [[bt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            DeviceBindGuideVC *vc = [storyboard instantiateViewControllerWithIdentifier:@"DeviceBindGuideVCID"];
            [vc setHiddenNextBt:YES];
            [self.navigationController pushViewController:vc animated:NO];
        }];
        [topBar addSubview:bt];
    }
    UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, 44)];
    titleLb.text = @"扫描二维码";
    [titleLb setTextColor:[UIColor whiteColor]];
    [titleLb setTextAlignment:NSTextAlignmentCenter];
    [titleLb setFont:[UIFont boldSystemFontOfSize:16]];
    [topBar addSubview:titleLb];
    
    //提示标签
    NSString *text = @"将扫描框对准屏幕上的二维码";
    float tw =  getTextWidth(text, KMainW, 16);
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(KMainW/2-tw/2, CGRectGetMaxY(scanView.frame) + padding+20, tw, labelH)];
    label.text = @"将扫描框对准屏幕上的二维码";
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:16.0f];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [self.view addSubview:label];
    label = [[UILabel alloc] initWithFrame:CGRectMake(KMainW/2-tw/2, CGRectGetMaxY(scanView.frame) + padding+labelH+24, tw, labelH*2)];
    label.text = @"1.请保证手机正常联网\n2.扫描确认关联后即可使用";
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:14.0f];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor whiteColor];
    [self.view addSubview:label];
}

- (void)setupCamera {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //初始化相机设备
        self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        //初始化输入流
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
        
        //初始化输出流
        AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
        //设置代理，主线程刷新
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        //初始化链接对象
        self.session = [[AVCaptureSession alloc] init];
        //高质量采集率
        [self.session setSessionPreset:AVCaptureSessionPresetHigh];
        
        if ([self.session canAddInput:input]) [self.session addInput:input];
        if ([self.session canAddOutput:output]) [self.session addOutput:output];
        
        //条码类型（二维码/条形码）
        output.metadataObjectTypes = [NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil];
        
        //更新界面
        dispatch_async(dispatch_get_main_queue(), ^{
            self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
            self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
            self.preview.frame = CGRectMake(0, 0, KMainW, KMainH);
            [self.view.layer insertSublayer:self.preview atIndex:0];
            [self.session startRunning];
        });
    });
}

- (void)addTimer {
    _distance = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction {
    if (_distance++ > KMainW * 0.65) _distance = 0;
    _line.frame = CGRectMake(0, _distance, KMainW * 0.65, 2);
}

- (void)removeTimer {
    [_timer invalidate];
    _timer = nil;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    //扫描完成
    if ([metadataObjects count] > 0) {
        //显示结果
        NSString *text = [[metadataObjects firstObject] stringValue];
        NSLog(@"扫描结果：%@", text);
        [self binding:text];
    }
}

- (void)stopScanning {
    [self.session stopRunning];
    self.session = nil;
    [self.preview removeFromSuperlayer];
    [self removeTimer];
}

- (void)dialog:(int) type text:(NSString *)txt{
    NSString *title = type==0 ? @"√ 设备绑定成功！" : @"! 绑定未成功！";
    NSString *cancelTxt = type==0 ? @"确定" : @"退出";
    NSString *confirmTxt = type==0 ? @"继续绑定" : @"重试";
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:title message:txt preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelTxt style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (self->isBindOk && !self->isFromLoadingVC) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"TabBarControllerID"];
            [self.navigationController pushViewController:vc animated:NO];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:confirmTxt style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        self->isBinding = NO;
    }];
    [vc addAction:cancel];
    [vc addAction:confirm];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)binding:(NSString *)text {
    if (isBinding) {
        return;
    }
    isBinding = YES;
    [self changeState:2 msg:nil];
    NSDictionary *dic = @{@"bindingKey": text};
    [[[HttpRequest shareInstance] signPost:d_device_binding map:[NSMutableDictionary dictionaryWithDictionary:dic]] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            [self changeState:1 msg:nil];
            self->isBindOk = YES;
            [self dialog:0 text:nil];
        } else {
            [self changeState:3 msg:x[@"message"]];
            [JPToast showText:x[@"message"]];
            [self dialog:1 text:x[@"message"]];
//            [self performSelector:@selector(retry) withObject:nil afterDelay:2];
        }
    } error:^(NSError *error) {
        [self changeState:3 msg:nil];
        [self dialog:1 text:@"绑定失败"];
//        [self performSelector:@selector(retry) withObject:nil afterDelay:2];
    }];
}

- (void)changeState:(int)status msg:(NSString *)msg {
    if (status != 0) {
        [self.conView setHidden:YES];
    } else {
        [self.conView setHidden:YES];
        return;
    }
    switch (status) {
        case 1: {
            isAni = NO;
            self.stateIv.transform = CGAffineTransformMakeRotation(0);
            self.stateIv.image = [UIImage imageNamed:@"right"];
            self.stateLb.text = @"设备绑定成功";
            break;
        }
        case 2: {
            isAni = YES;
            [self startAnimation];
            self.stateIv.image = [UIImage imageNamed:@"loading"];
            self.stateLb.text = @"设备绑定中";
            break;
        }
        case 3: {
            isAni = NO;
            self.stateIv.transform = CGAffineTransformMakeRotation(0);
            self.stateIv.image = [UIImage imageNamed:@"error"];
            self.stateLb.text = msg && msg.length>8 ? msg : @"绑定失败";
            break;
        }
        default:
            break;
    }
}

//- (void)retry {
//    isBinding = NO;
//}

- (void)startAnimation {
    CGAffineTransform endAngle = CGAffineTransformMakeRotation(angle * (M_PI /180.0f));
    [UIView animateWithDuration:0.04 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.stateIv.transform = endAngle;
    } completion:^(BOOL finished) {
        self->angle += 20;
        if (self->isAni) {
            [self startAnimation];
        }
    }];
}

////提示弹窗
//- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message sureHandler:(void (^)())sureHandler cancelHandler:(void (^)())cancelHandler {
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:sureHandler];
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:cancelHandler];
//    [alertController addAction:sureAction];
//    [alertController addAction:cancelAction];
//
//    [self presentViewController:alertController animated:YES completion:nil];
//}

//绘制角图片
- (void)drawImageForImageView:(UIImageView *)imageView {
    UIGraphicsBeginImageContext(imageView.bounds.size);
    
    //获取上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //设置线条宽度
    CGContextSetLineWidth(context, 6.0f);
    //设置颜色
    CGContextSetStrokeColorWithColor(context, [[UIColor greenColor] CGColor]);
    //路径
    CGContextBeginPath(context);
    //设置起点坐标
    CGContextMoveToPoint(context, 0, imageView.bounds.size.height);
    //设置下一个点坐标
    CGContextAddLineToPoint(context, 0, 0);
    CGContextAddLineToPoint(context, imageView.bounds.size.width, 0);
    //渲染，连接起点和下一个坐标点
    CGContextStrokePath(context);
    
    imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

//绘制线图片
- (void)drawLineForImageView:(UIImageView *)imageView {
    CGSize size = imageView.bounds.size;
    UIGraphicsBeginImageContext(size);
    
    //获取上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //创建一个颜色空间
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    //设置开始颜色
    const CGFloat *startColorComponents = CGColorGetComponents([[UIColor greenColor] CGColor]);
    //设置结束颜色
    const CGFloat *endColorComponents = CGColorGetComponents([[UIColor whiteColor] CGColor]);
    //颜色分量的强度值数组
    CGFloat components[8] = {startColorComponents[0], startColorComponents[1], startColorComponents[2], startColorComponents[3], endColorComponents[0], endColorComponents[1], endColorComponents[2], endColorComponents[3]
    };
    //渐变系数数组
    CGFloat locations[] = {0.0, 1.0};
    //创建渐变对象
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
    //绘制渐变
    CGContextDrawRadialGradient(context, gradient, CGPointMake(size.width * 0.5, size.height * 0.5), size.width * 0.25, CGPointMake(size.width * 0.5, size.height * 0.5), size.width * 0.5, kCGGradientDrawsBeforeStartLocation);
    //释放
    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(gradient);
    
    imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end

